<?php

namespace app\shop\model\user;

use app\shop\exception\FailException;
use app\shop\model\BaseModel;
use app\shop\model\goods\GoodsModel;
use app\shop\model\goods\GoodsSkuModel;
use think\Model;
use think\model\relation\BelongsTo;

class UserCartModel extends BaseModel
{
    protected $name = 'shop_user_cart';

    /**
     * 查询范围：用户ID
     * @param $query
     * @return mixed
     * @noinspection PhpMissingReturnTypeInspection
     */
    public function scopeUserId($query)
    {
        return $query->where([
            ['user_id', '=', request()->user['id']]
        ]);
    }

    /**
     * 关联商品
     * @return BelongsTo
     */
    public function goods(): BelongsTo
    {
        return $this->belongsTo(GoodsModel::class, 'goods_id', 'id');
    }

    /**
     * 关联SKU
     * @return BelongsTo
     */
    public function sku(): BelongsTo
    {
        return $this->belongsTo(GoodsSkuModel::class, 'sku_id', 'id');
    }

    /**
     * 通过ID获取商品信息
     * @param int $id
     * @return UserCartModel|array|mixed|Model
     * @throws FailException
     * @noinspection PhpUnused
     */
    public static function getInfoById(int $id): mixed
    {
        $info = self::where(['id' => $id])->findOrEmpty();

        if ($info->isEmpty()) {
            throw new FailException('购物车商品已被删除,请刷新');
        }

        return $info;
    }
}
